package com.dsg.util;

import com.dsg.common.util.toolbox.StringUtil;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {


    // public static final String DEFAULT_404_VIEW = "/pages/404";
    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(RRException.class)
    public R handleRRException(RRException e) {
        R r = new R();
        r.put("code", e.getCode());
        r.put("message", e.getMessage());
        return r;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return R.error("數據庫中已存在該記錄");
    }

    @ExceptionHandler(AuthorizationException.class)
    public R handleAuthorizationException(AuthorizationException e) {
        logger.error(e.getMessage(), e);
        return R.error("沒有權限，請聯繫管理員授權");
    }

    @ExceptionHandler(SessionException.class)
    public R handleSessionException(SessionException e) {
        R r = new R();
        r.put("code", e.getCode());
        r.put("message", e.getMessage());
        logger.error(e.getMessage(), e);
        return r;
    }

    @ExceptionHandler(VersionException.class)
    public R handleVersionException(VersionException e) {
        R r = new R();
        r.put("code", e.getCode());
        if (StringUtil.isNotEmpty(e.getMessage())) {
            r.put("message", e.getMessage());
        } else {
            r.put("message", "數據已更新，請刷新後再操作！");
        }
        logger.error(e.getMessage(), e);
        return r;
    }

    /**
     * 添加全局异常处理流程，根据需要设置需要处理的异常
     *
     * @param request
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object methodArgumentNotValidHandler(HttpServletRequest request, Exception exception) throws Exception {// 记录异常日志
        String msg = exception.getMessage();
        logger.error(msg, exception);
        if (StringUtil.isNotEmpty(msg)) {
            return R.error(msg);
        } else {
            return R.error();
        }
    }

    // @ExceptionHandler(value = NoHandlerFoundException.class)
    // @ResponseStatus(HttpStatus.NOT_FOUND)
    // public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception
    // e) throws Exception {
    // logger.info("找不到页面...");
    // ModelAndView mav = new ModelAndView();
    // mav.addObject("exception", e);
    // mav.addObject("url", req.getRequestURL());
    // mav.setViewName(DEFAULT_404_VIEW);
    // return mav;
    // }

}